package org.example.service.client;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import org.example.HelloServiceGrpc;
import org.example.helloProto;

import java.util.concurrent.TimeUnit;

/**
 * @Author : 叶荻风
 * @create : 2024/6/21 11:25
 */
public class GrpcClientClientStream {
    public static void main(String[] args) {
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost",9000).usePlaintext().build();
        HelloServiceGrpc.HelloServiceStub helloServiceStub = HelloServiceGrpc.newStub(managedChannel);

        StreamObserver<helloProto.HelloRequest> helloRequestStreamObserver =
                helloServiceStub.s2cs(new StreamObserver<helloProto.HelloResponse>() { //监控响应数据
            @Override
            public void onNext(helloProto.HelloResponse value) {
                System.out.println("服务端响应数据为"+value.getUsername());

            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onCompleted() {
                System.out.println("服务器响应一次");
            }
        });
        for (int i = 0; i < 10; i++) {
            helloProto.HelloRequest.Builder builder = helloProto.HelloRequest.newBuilder();
            helloProto.HelloRequest request = builder.setUsername("difeng" + i).build();
            helloRequestStreamObserver.onNext(request);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        helloRequestStreamObserver.onCompleted();
        try {
            managedChannel.awaitTermination(12, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        managedChannel.shutdown();

    }
}
